<?php

namespace Plu\qdh\Services;

use Plu\qdh\Services\ServiceBase;
use Plu\qdh\Services\ProductService;
use Plu\qdh\Models\App\Order;
use Plu\qdh\Models\App\Project;
use Plu\qdh\Models\App\Product;
use Plu\qdh\Models\App\Report;

class ReportService extends ServiceBase {


    public function productRerpot($limit, $offset) {
        list($count, $items) = Product::getItems($limit, $offset);
        return [$count, $items];
    }

    public function getIndexReport() {

        $finishOrders  = $this->getOrderReport([
            \OrderConst::ORDER_STATUS['published'],
            \OrderConst::ORDER_STATUS['used'],
        ]);

        $refoundOrders = $this->getOrderReport([\OrderConst::ORDER_STATUS['refind']]);

        $productReport = $this->getProductRerpot();

        $data = [
            'finishOrders'  => $finishOrders[0],
            'refoundOrders' => $refoundOrders[0],
            'productReport' => $productReport
        ];
        return $data;
    }

    // 付款详情报表
    public function getOrderReport($status) {

        $status = join(",", $status);

        $sql = "SELECT
            count(1) as orderCount,
            sum(totalPrice) as allPrice,
            sum(spreadPrize * num) as allSpreadPrize,
            sum(SettlementPrice * num) as defaultPrice
            FROM Plu\qdh\Models\App\Order
            WHERE status in ($status)
        ";

        $modelsManager = $this->getDI()->getModelsManager();

        $items = $modelsManager->executeQuery($sql);

        if ($items) {
            $items = $items->toArray();
            return $items;
        }

        return [];

    }

    public function getProductRerpot() {
        $productCount = Product::getCount();
        $projectCount = Project::getCount();
        return [
            'productCount' => $productCount,
            'projectCount' => $projectCount
        ];
    }

    public function payOrderReport($orderObj) {
        $productNo = $orderObj->productNo;
        $product   = Product::getItemByProductNo($productNo);
        $product->payCount = $product->payCount + $orderObj->num;
        $product->save();
    }


    public function refoundOrderReport() {
        $productNo = $orderObj->productNo;
        $product   = Product::getItemByProductNo($productNo);
        $product->payCount = $product->refoundCount + $orderObj->num;
        $product->save();
    }


    public function getCustReport($custId, $day) {
        
        $startTime = date('Y-m-01', strtotime($day));;

        $endTime   = date('Y-m-d', strtotime("$startTime +1 month -1 day"));

        $items = Report::getReport($custId, $startTime, $endTime);

        return $items;

    }






}